#include "Seq.h"
#include <fstream>

using namespace std;

CSeq::CSeq()
{
	m_ppOrigPixelArray = NULL;
	m_ppRecPixelArray = NULL;
}

CSeq::~CSeq()
{
	if( m_ppOrigPixelArray != NULL )
	{
		for ( int i=0; i<m_iFrameCount; i++ )
		{
			delete [] m_ppOrigPixelArray[i];
		}

		delete [] m_ppOrigPixelArray;
	}

	if( m_ppRecPixelArray != NULL )
	{
		for ( int i=0; i<m_iFrameCount; i++ )
		{
			delete [] m_ppRecPixelArray[i];
		}

		delete [] m_ppRecPixelArray;
	}
}

bool CSeq::InitFromFile( string orig_seq_file, string rec_seq_file, int width, int height, int frame_count )
{
	m_strOrigFile = orig_seq_file;
	m_strRecFile = rec_seq_file;
	m_iWidth = width;
	m_iHeight = height;
	m_iFrameCount = frame_count;

	if ( !ReadSeqFromFile( m_ppOrigPixelArray, orig_seq_file ) ) return false;
	if ( !ReadSeqFromFile( m_ppRecPixelArray, rec_seq_file ) ) return false;

	m_ppIntPixelArray = new unsigned char *[m_iFrameCount];
	for ( int i=0; i<m_iFrameCount; i++ )
	{
		m_ppIntPixelArray[i] = new unsigned char[m_iWidth*m_iHeight];
		memset( m_ppIntPixelArray[i], 0, m_iWidth*m_iHeight*sizeof( unsigned char ) );

		for ( int y=0; y<m_iHeight; y++ )
		{
			for ( int x=0; x<m_iWidth; x+=2 )
			{
				m_ppIntPixelArray[i][y*m_iWidth+x] = m_ppRecPixelArray[i][y*m_iWidth+x];
			}
		}

	}

	return true;

}



bool CSeq::ReadSeqFromFile( unsigned char ** &pixel_array, string seq_file )
{

	pixel_array = new unsigned char *[m_iFrameCount];

	fstream infile;
	infile.open( seq_file.c_str(), ios::binary|ios::in );
	if ( !infile.is_open() )
	{
		return false;
	}

	for ( int i=0; i<m_iFrameCount; i++ )
	{
		pixel_array[i] = new unsigned char[m_iWidth*m_iHeight];
		infile.read( (char*)pixel_array[i], m_iWidth*m_iHeight );

		if ( infile.eof() )
		{
			infile.close();
			return false;
		}
	}

	infile.close();
	return true;
}
